//
//  Kratos_MainViewControllerPresenter.m
//  kratos_framework_Example
//
//  Created by 7yao.top on 2018/10/25.
//  Copyright © 2018年 kratos_framework. All rights reserved.
//

#import "Kratos_MainViewControllerPresenter.h"
#import "Kratos_LongZhuLogin.h"
#import "k_const.h"
#import "Kratos_MainViewController.h"
#import "Kratos_ForgotVC.h"
#import "Kratos_QuickLoginVC.h"
#import "Kratos_HttpConfigure.h"
#import "Kratos_Options.h"
#import "AFNetworking.h"
#import "Kratos_HttpResponse.h"
#import "Kratos_userInfo.h"
#import "YYModel.h"


@interface Kratos_MainViewControllerPresenter ()
@end;


@implementation Kratos_MainViewControllerPresenter


- (instancetype)initWithView:(id)view
{
    self = [super initWithView:view];
    if (self) {
        
       Kratos_Options  *option = [Kratos_HttpConfigure sharedHttpConfigure].Kra_option;
        
        NSString *key = @"isFirstLogin";
        BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:key];
        if (!isFirst) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self Kratos_getChid:option];
        }else
        {
            
        }
            
    
        
    }
    return self;
}

- (void)Kratos_getChid:(Kratos_Options *)option
{
    
//    NSString *initCallBackStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"InitCallBack"];
//    if ([initCallBackStr isEqualToString:@"NO"]) return;
    
    if ([Kratos_Tool Kratos_getCallback_Kratos] == false) return;
    
    NSMutableString *sss =  [NSMutableString stringWithString:@"https://api.lzgame.top"];
    [sss appendFormat:@"/app/repact?"];
    [sss appendFormat:@"inm=1&"];
    [sss appendFormat:@"gameid=%@&",option.Kratos_GameID];
    [sss appendFormat:@"cid=%@&",option.Kratos_CID];
    [sss appendFormat:@"exmodel=%@&",option.Kratos_exmodel];
    [sss appendFormat:@"username=%@&",option.Kratos_idfa];
    [sss appendFormat:@"username=%@&",option.Kratos_idfa];
    [sss appendFormat:@"pkg=%@&",option.Kratos_pkg];
    [sss appendFormat:@"version=%@&",option.Kratos_version];
    [sss appendFormat:@"idfa=%@&",option.Kratos_idfa];
    [sss appendFormat:@"sdkver=%@",option.Kratos_sdkver];
    
    
    
    AFHTTPSessionManager *session =  [AFHTTPSessionManager  manager];
     AFHTTPRequestSerializer * requestSerializer = [AFHTTPRequestSerializer serializer];
    [requestSerializer setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
    [requestSerializer setValue:@"http://game.lzgame.top" forHTTPHeaderField:@"Origin"];
    session.requestSerializer = requestSerializer;
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [session POST:sss parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        kLog(@"success%@",responseObject);
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            [[NSUserDefaults standardUserDefaults] setObject:[responseObject objectForKey:@"chid"] forKey:@"chid"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
      
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        kLog(@"failure%@",error);
    }];
    
    
    
}

- (void)Kratos_presentVC
{
    UIViewController *vc =  (UIViewController *)_view1;
    [vc presentViewController:[[Kratos_LongZhuLogin alloc]init] animated:false completion:nil];
    
}

///获取验证码
- (void)Kratos_getmsgCode:(NSString *)phonenum
{
    
    
    __weak typeof(self) weakSelf = self;
    
    [self.Kra_httpClient Kratos_noGeneralpost:[NSString stringWithFormat:@"/index/pub/smsrqcode?username=%@&type=3",phonenum] Kratos_parameters:nil onSuccess:^(Kratos_HttpResponse * _Nullable response) {
       
        if (response.Kra_status == Kratos_HttpResponseStatusSuccess)
        {
            if ([response.Kra_content isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dict = response.Kra_content;
                [weakSelf.view1 makeToast:dict[@"msg"]];
            }
            
        }
        
    } onFail:^(Kratos_HttpResponse * _Nullable response) {
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"stopCountDown" object:nil];
        [weakSelf.view1 makeToast:response.Kra_content];
        
    }];
}
// 手机号 + 短信码 登录
- (void)Kratos_loginWithUserName:(NSString *)userName Kratos_code:(NSString *)code
{
    __weak typeof(self) weakSelf = self;
    
    UIViewController *vc = weakSelf.view1;

    if (userName.length == 0 || userName == nil) {
        [vc.view  makeToast:@"请输入验证码"];
        return;
    }
    if (code.length == 0 || code == nil) {
        [vc.view  makeToast:@"请输入手机号码"];
        return;
    }
    

    
    [self.Kra_httpClient Kratos_post:@"/user/pub/mobilesmsapi" Kratos_parameters:@{@"username":userName,@"sms":code,@"type":@"3"} Kratos_onSuccess:^(Kratos_HttpResponse * _Nullable response) {
        if (response.Kra_status == Kratos_HttpResponseStatusSuccess) {
           Kratos_userInfo * userInfo =  [[Kratos_userInfo alloc] initWithDict:response.Kra_content[@"data"]];
//            Kratos_userInfo * userInfo = [Kratos_userInfo  yy_modelWithDictionary:response.content[@"data"]];
            [userInfo Kratos_saveinfo_Kratos];
        }
    } Kratos_onFail:^(Kratos_HttpResponse * _Nullable response) {
        if ([weakSelf.view1 isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = weakSelf.view1;
            [vc.view makeToast:response.Kra_content];
        }        
    }];

    
}




- (void)Kratos_dissmissVC{
    UIViewController *vc =  (UIViewController *)_view1;
    [vc dismissViewControllerAnimated:false completion:nil];
}

- (void)Kratos_loginClick:(UIButton *)btn{
    
    if ([_view1 isKindOfClass:[Kratos_MainViewController class]]) {
        [self saveAccount];
        
        
        
    }else if ([_view1 isKindOfClass:[Kratos_LongZhuLogin class]])
    {
        [self saveAccount];
    }

}

- (void)saveAccount
{
    Kratos_MainViewController *mian = (Kratos_MainViewController*)_view1;
    kLog(@"%@",mian.accountView.Kra_inputView.Kra_phoneInput.Kra_textField.text);
    NSString *str = mian.accountView.Kra_inputView.Kra_phoneInput.Kra_textField.text;
    if (str != nil && str.length > 0)
    {
        NSString *key = [NSString stringWithFormat:@"%@", [mian.accountView.Kra_inputView.Kra_phoneInput Kra_caller]];
        NSString*cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject] stringByAppendingString:key];
        
        if (![[NSFileManager defaultManager]fileExistsAtPath:cachePath])
        {
            NSMutableArray *att = [NSMutableArray array];
            [att addObject:str];
            [att writeToFile:cachePath atomically:YES];
            
        }else
        {
            NSMutableArray *mArray = [NSMutableArray arrayWithContentsOfFile:cachePath];
            [mArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![obj isEqualToString:str])
                {
                    [mArray addObject:str];
                }
            }];
            if (mArray.count==0) {
                [mArray addObject:str];
            }
            [mArray writeToFile:cachePath atomically:YES];
        }
    }
}

- (void)Kratos_forgetPwdClick:(UIButton *)btn
{
    kLog(@"forgetPwdClick");
    
    Kratos_ForgotVC *forgotVC =   [[Kratos_ForgotVC alloc]init];
    if ([_view1 isKindOfClass:[Kratos_LongZhuLogin class]])
    {
        [_view1 presentViewController:forgotVC animated:false completion:nil];
    }
}

- (void)Kratos_regiterButtonClick:(UIButton *)btn
{
    
}

- (void)Kratos_quickButtonClick:(UIButton *)btn
{
    kLog(@"quickButtonClick");
    Kratos_QuickLoginVC *quick = [[Kratos_QuickLoginVC alloc]init];
    [_view1 presentViewController:quick animated:false completion:nil];
}
@end
